package com.orcamento.entity;

import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import com.orcamento.entity.model.Payment;
import com.orcamento.util.Money;

@Entity
@Table(name="parcela")
public class Installment {
	
	@Id
	@SequenceGenerator(name="installment_id", sequenceName="installment_id")
	@GeneratedValue(generator="installment_id", strategy=GenerationType.AUTO)
	private Long id;
	@Column(name="ItNumeroParcela", nullable=false)
	private Integer installmentNumber;
	@Embedded
	@AttributeOverride(name="value", column=@Column(name="FoValor"))
	private Money value;
	
	@ManyToOne(targetEntity=Invoice.class)
	@JoinColumn(name="IDFatura", referencedColumnName="IDFatura", nullable=false)
	private Invoice invoice;
	@ManyToOne(targetEntity=Spent.class)
	@JoinColumn(name="IDPerda", referencedColumnName="IDPerda", nullable=false)
	private Spent spent;
	
	public Installment() { }
	
	public Installment(Integer installmentNumber, Money value, Spent spent, Invoice invoice) {
		this.installmentNumber = installmentNumber;
		this.value = value;
		this.spent = spent;
		this.invoice = invoice;
	}
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public Integer getInstallmentNumber() {
		return installmentNumber;
	}
	public void setInstallmentNumber(Integer installmentNumber) {
		this.installmentNumber = installmentNumber;
	}
	public Invoice getInvoice() {
		return invoice;
	}
	public void setInvoice(Invoice invoice) {
		this.invoice = invoice;
	}
	public Spent getSpent() {
		return spent;
	}
	public void setSpent(Spent spent) {
		this.spent = spent;
	}
	public Money getValue() {
		return value;
	}
	public void setValue(Money value) {
		this.value = value;
	}

	public Payment toPayment() {
		return new Payment(id, value, getSpent().getSpentDay(), getSpent().getEvent().getName(), "PARCELADO", getSpent().getNumberInstallments(), getInstallmentNumber());
	}

	public void refund(Money refundValue) {
		value = value.minus(refundValue);
		spent.setValue( spent.getValue().minus(refundValue) );
	}

}
